<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>简易聊天室</title>
    <link href="../public/css/bootstrap.min.css" rel="stylesheet">
    <link href="../public/css/style.css?v=3" rel="stylesheet">
    <script type="text/javascript" src="../public/js/swfobject.js"></script>
    <script type="text/javascript" src="../public/js/web_socket.js"></script>
    <script src="http://cdn.bootcss.com/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://cdn.bootcss.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="../public/js/common.js"></script>
    <script type="text/javascript" src="../public/js/recordLog.js"></script>
    <script type="text/javascript">
        if (typeof console == "undefined") {    this.console = { log: function (msg) {  } };}
        WEB_SOCKET_SWF_LOCATION = "../public/swf/WebSocketMain.swf";
        WEB_SOCKET_DEBUG = true;
        var ws, client_list={};
        var name = "<{$user_name}>";
        var room_id = "<{$room_id}>";
        //var allUserList = "<{$allUserImageId}>"; 废除掉，现在的用户实时头像是实时推送过来，防止有延迟头像问题
        $(function() {
            select_client_id = 'all';
            $("#client_list").change(function () {
                select_client_id = $("#client_list option:selected").attr("value");
            });
            scroolDialog();
            getChatLogToday(room_id);
        });

            // 连接服务端
            function connect() {
                // 创建websocket
                ws = new WebSocket("ws://" + document.domain + ":7272");
                ws.onopen = onopen;
                // 当有消息时根据消息类型显示不同信息
                ws.onmessage = onmessage;
                ws.onclose = function () {
                    console.log("连接关闭，定时重连");
                    connect();
                };
                ws.onerror = function () {
                    console.log("出现错误");
                };
            }

            // 连接建立时发送登录信息
            function onopen() {
                // 登录
                var login_data = {};
                login_data["type"] = "login";
                login_data["client_name"] = name;
                login_data["room_id"] = room_id;
                console.log("websocket握手成功，发送登录数据:" + login_data);
                if(name) {
                    ws.send(JSON.stringify(login_data));
                }else{
                    login_data["type"] = "passer_enter";//路人进入了
                    ws.send(JSON.stringify(login_data));
                }
            }

            // 服务端发来消息时
            function onmessage(e) {
                var data = eval("(" + e.data + ")");
                switch (data['type']) {
                    // 服务端ping客户端
                    case 'ping':
                        ws.send('{"type":"pong"}');
                        break;
                    // 登录 更新用户列表
                    case 'login':
                        if(data['client_list'])
                        {
                            client_list = data['client_list'];
                        }
                        else
                        {
                            client_list[data['client_id']] = data['client_name'];
                        }
                        flush_client_list();
                        joinRoom(data['client_name'] + ' 加入了聊天室');
                        console.log(name + "登录成功");
                        break;
                    // 发言
                    case 'say':
                        say(data['from_client_id'], data['from_client_name'], data['content'], data['time'],data['photoList']);
                        console.log(name + "说话成功");
                        break;
                    // 用户退出 更新用户列表
                    case 'logout':
                        delete client_list[data['from_client_id']];
                        flush_client_list();
                        if(data['from_client_name']) { //不是游客，则提示别人退出聊天室
                            joinRoom(data['from_client_name'] + ' 退出聊天室');
                        }
                        console.log(name + "退出成功");
                        break;
                    case 'passer_enter': //为路人获取在线列表
                        if(data['client_list'])
                        {
                            client_list = data['client_list'];
                        }
                        flush_client_list();
                        break;
                }
            }

            // 提交对话
            function onSubmit() {
                var input = document.getElementById("textarea");
                var to_client_id = $("#client_list option:selected").attr("value");
                var to_client_name = $("#client_list option:selected").text();
                var data = {};
                data["type"] = "say";
                data["to_client_id"] = to_client_id;
                data["to_client_name"] = to_client_name;
                data["content"] = input.value;
                if(name) {
                    ws.send(JSON.stringify(data));
                    input.value = "";
                    input.focus();
                }else{
                    alert("登录才能发言!");
                }
            }

            // 刷新在线用户列表 和 私聊对话用户列表
            function flush_client_list() {
                var userlist_window = $("#userlist");
                var client_list_slelect = $("#client_list");
                userlist_window.empty();
                userlist_window.append('<h4>在线用户</h4><ul>');
                client_list_slelect.empty();
                client_list_slelect.append('<option value="all" id="cli_all">所有人</option>');
                //过滤掉不同浏览器登陆的同一个用户
                var user_list = new Object();
                for(var p in client_list){
                    user_list[client_list[p]] = p; //倒叙保证唯一用户
                }
                for(var u in user_list){
                    userlist_window.append('<li id="'+user_list[u]+'">'+u+'</li>');
                    if(u != name && u) {
                        client_list_slelect.append('<option value="' + user_list[u] + '">' + u + '</option>');
                    }
                }
                $("#client_list").val(select_client_id);
                userlist_window.append('</ul>');
            }

            // 发言
            function say(from_client_id, from_client_name, content, time ,photoList) {
                if(photoList) {
                    console.log(photoList);
                    //var allUser = JSON.parse(decodeURIComponent(photoList));
                    console.log(photoList[from_client_name]);
                    if(photoList[from_client_name]){
                        image_id = photoList[from_client_name];
                    }else{
                        image_id = 1;
                    }
                }else{
                    image_id = 1;
                }
                $("#dialog").append('<div class="speech_item"><div class="msg_left"><img src="../public/img/user_image/' + image_id + '.png" class="user_icon" /> ' + from_client_name + ' <br> ' + time + '</div><div class="msg_right"><p class="triangle-isosceles top">' + content + '</p></div></div>');
                scroolDialog();
            }

            //加入聊天室
            function joinRoom(content) {
                $("#dialog").append('<div class="speech_item"><p class="triangle-isosceles top">' + content + '</p></div>');
                scroolDialog();
            }
    </script>
</head>
<body onload="connect();">
<nav class="navbar navbar-default navbar-static-top" role="navigation">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="#">简易聊天室</a>
        </div>
        <div id="navbar" class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
<!--            这里是一个导航栏，暂时前面不需要这么多导航按钮，需要的时候再展示出来
                <li class="active"><a href="#">Home</a></li>
                <li><a href="#about">About</a></li>
                <li><a href="#contact">Contact</a></li>
                <li class="dropdown">
                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <span class="caret"></span></a>
                    <ul class="dropdown-menu" role="menu">
                        <li><a href="#">Action</a></li>
                        <li><a href="#">Another action</a></li>
                        <li><a href="#">Something else here</a></li>
                        <li class="divider"></li>
                        <li class="dropdown-header">Nav header</li>
                        <li><a href="#">Separated link</a></li>
                        <li><a href="#">One more separated link</a></li>
                    </ul>
                </li>-->
            </ul>
            <{if $isLogin}>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="#">欢迎你,<{$user_name}></a></li>
                <li><a href="?_c=login&_a=unlogin">退出</a></li>
                <!--<li><a href="?_c=index&_a=refresh&type=authRedis&key=<{$room_id}>_user_list">刷新在线</a></li>-->
            </ul>
            <{else}>
            <ul class="nav navbar-nav navbar-right">
                <li><a href="?_c=register&_a=regi">注册</a></li>
                <li><a href="?_c=login&_a=login">登录</a></li>
            </ul>
            <{/if}>
        </div>
    </div>
</nav>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-1 column">
        </div>
        <div class="col-md-6 column">
            <div class="thumbnail">
                <div class="caption" id="dialog"></div>
            </div>
            <form onsubmit="onSubmit(); return false;">
                <select style="margin-bottom:8px" id="client_list">
                    <option value="all">所有人</option>
                </select>
                <textarea class="textarea thumbnail" id="textarea"></textarea>
                <div class="say-btn"><input type="submit" class="btn btn-default" value="发表" /></div>
            </form>
        </div>
        <div class="col-md-2 column">
            <div class="thumbnail">
                <div class="caption" id="userlist">
                </div>
            </div>
        </div>

        <div class="col-md-2 column">
            <div class="thumbnail">
                <div class="caption" id="roomlist">
                    <h4>当前：<span style="color: red"><{$room_name}></span></h4>
                    <br>
                    <h4>房间列表</h4>
                    <ul></ul>
                    <{foreach from=$roomList key=r_id item=r_name}>
                    <li><a href="/?room_id=<{$r_id}>"><{$r_name}></a></li>
                    <{/foreach}>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/javascript" language=JavaScript charset="UTF-8">
    document.onkeydown = function(event){
        var e = event || window.event || arguments.callee.caller.arguments[0];
        if(e && e.keyCode==13){ // 用户按下enter键就发言
            onSubmit();
        }
    };
</script>
</html>
